/* eslint-disable array-callback-return */
import React from 'react';
import { DownloadOutlined, PlusOutlined, UploadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Input, Table, Select, DatePicker, message, Modal, Row, Divider } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import downloadFile, { matchDict } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ loading }) => ({
  loading: loading.models.custedit,
}))
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      nowPage: 1,
      pageNum: 10,
      cmTotal: 10,
      custId: null,
      genderList: [],
      hasChildList: [],
      selectedRowKeys: [],
      isAdd: true,
      modalVisible: false,
    };

    this.columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '性别',
        dataIndex: 'gender',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '职位',
        dataIndex: 'position',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '手机号码',
        dataIndex: 'phoneNo',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '固定电话',
        dataIndex: 'tel',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: 'QQ',
        dataIndex: 'qq',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '微信',
        dataIndex: 'wx',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '地址',
        dataIndex: 'addr',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '生日',
        dataIndex: 'birthDay',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD') : ''),
      },
      {
        title: '是否有小孩',
        dataIndex: 'hasChild',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '备注',
        dataIndex: 'remark',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: (text, record) => (
          <span className="editable-row-operations">
            <a onClick={e => this.update(e, record.contPerId)}>修改</a>
            <Divider type="vertical" />
            <a onClick={e => this.delList(e, record)}>删除</a>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { nowPage, pageNum } = this.state;
    const { custId, genderList, hasChildList } = this.props;
    this.setState({ custId, genderList, hasChildList }, () => {
      this.getList(nowPage, pageNum);
    });
  };

  // 获取列表数据
  getList = (nowPage, pageNum) => {
    const { custId, dispatch } = this.props;
    const { genderList, hasChildList } = this.state;
    const pageArg = {
      currentPage: nowPage,
      pageSize: pageNum,
      orderBy: ' CONT_PER_ID DESC',
    };
    const params = { custId, pageArg };
    dispatch({
      type: 'custedit/getContactsList',
      payload: params,
    }).then(res => {
      if (res.success) {
        const data = res.data.pageRecords;
        data.map(item => {
          const temp = item;
          temp.gender = matchDict(genderList, item.gender);
          temp.hasChild = matchDict(hasChildList, item.hasChild);
        });
        setTimeout(() => {
          this.setState({ dataSource: data, cmTotal: res.data.totalCount });
        }, 0);
      } else {
        this.setState({ cmTotal: 0, dataSource: [] });
        message.warning(`${res.message || '暂无数据！'}`);
      }
    });
  };

  // 删除数据
  delList = (e, record) => {
    e.preventDefault();
    const { selectedRowKeys } = this.state;
    const { dispatch } = this.props;
    const rowKeys = [];
    const rows = [];
    rowKeys.push(record.contPerId);
    rows.push(record);
    this.setState({ selectedRowKeys: rowKeys });
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要刪除此条联系人信息吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'custedit/deleteContacts',
          payload: {
            generalIds: rowKeys,
          },
        }).then(res => {
          if (res.success) {
            const { cmTotal, nowPage, pageNum } = this.state;
            const selectedLen = selectedRowKeys.length;
            if (nowPage > 1 && (cmTotal % pageNum === selectedLen || pageNum === selectedLen)) {
              this.getList(nowPage - 1, pageNum);
              this.setState({ nowPage: nowPage - 1 });
            } else {
              this.getList(nowPage, pageNum);
            }
            this.setState({ selectedRowKeys: [] });
            message.success('删除成功！');
          } else {
            message.warning(`${res.message || '删除失败！'}`);
          }
        });
      },
    });
  };

  // 新增数据
  add = () => {
    const { form } = this.props;
    this.handleModalVisible(true, true);
    form.resetFields();
  };

  // 修改数据
  update = (e, contPerId) => {
    e.preventDefault();
    const { custId, dispatch, form } = this.props;
    const rowKeys = [];
    rowKeys.push(contPerId);
    this.setState({ selectedRowKeys: rowKeys });
    if (custId) {
      dispatch({
        type: 'custedit/getContacts',
        payload: {
          contPerId,
        },
      }).then(res => {
        this.setState({ custId });
        if (res.success && res.data) {
          this.handleModalVisible(true, false);
          const getFieldsList = form.getFieldsValue();
          Object.keys(res.data).forEach(key => {
            if (res.data[key]) {
              if (key === 'gender' || key === 'hasChild') {
                res.data[key] = `${res.data[key]}`;
              }
            }
          });
          Object.keys(getFieldsList).forEach(key => {
            if (res.data[key]) {
              if (key === 'gender' || key === 'hasChild') {
                form.setFieldsValue({ [key]: { key: res.data[key] } });
              } else if (key === 'birthDay') {
                form.setFieldsValue({ [key]: moment(res.data[key]) });
              } else {
                form.setFieldsValue({ [key]: res.data[key] });
              }
            }
          });
        } else {
          message.warning(`${res.message || '暂无数据！'}`);
        }
      });
    }
  };

  // 切换模态框：新增、修改
  handleModalVisible = (flag, isAdd) => {
    this.setState({
      modalVisible: !!flag,
      isAdd,
    });
  };

  // 取消关闭模态框
  cancelModal = () => {
    this.handleModalVisible(false, true);
    this.setState({ selectedRowKeys: [] });
  };

  // 新增修改提交数据
  submitData = () => {
    const { isAdd, custId, selectedRowKeys, nowPage, pageNum } = this.state;
    const { form, dispatch } = this.props;
    let submitData = {};
    const submitUrl = isAdd ? 'custedit/contactInsert' : 'custedit/contactUpdate';
    form.validateFieldsAndScroll((err, values) => {
      const temp = values;
      temp.birthDay = values.birthDay ? values.birthDay.format('YYYY-MM-DD') : '';
      if (!err) {
        Object.keys(values).forEach(key => {
          const obj = values;
          if (values[key] && values[key].key) {
            obj[key] = values[key].key;
          } else {
            obj[key] = values[key] ? values[key] : '';
          }
        });
        submitData = isAdd
          ? { custId, ...values }
          : { custId, ...values, contPerId: selectedRowKeys[0] };
        dispatch({
          type: submitUrl,
          payload: submitData,
        }).then(res => {
          this.setState({ modalVisible: false });
          if (res.success) {
            message.success(`${res.message || (isAdd ? '新增成功！' : '修改成功！')}`);
            this.getList(nowPage, pageNum);
            this.setState({ selectedRowKeys: [] });
          } else {
            message.warning(`${res.message || (isAdd ? '新增失败！' : '修改失败！')}`);
          }
        });
      }
    });
  };

  // 导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      confirm({
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { custId, selectedRowKeys } = this.state;
    const params = { custId, contPerIds: selectedRowKeys };
    downloadFile(params, '/csApi/contacts/expContact', 'POST');
  };

  render() {
    const {
      loading,
      dataSource,
      selectedRowKeys,
      modalVisible,
      isAdd,
      genderList,
      hasChildList,
      custId,
      nowPage,
      pageNum,
      cmTotal,
    } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    // 表格配置：行选择
    const rowSelection = {
      selectedRowKeys,
      onChange: rows => {
        this.setState({ selectedRowKeys: rows });
      },
    };
    // 表格配置：分页器
    const pagination = {
      defaultCurrent: nowPage, // 默认当前页
      defaultPageSize: pageNum, // 默认单页条数
      current: nowPage, // 当前页
      pageSize: pageNum, // 单页条数
      total: cmTotal, // 数据总数
      showQuickJumper: true, // 跳转至某页
      showSizeChanger: true, // 是否可以改变 pageSize
      onChange: (page, pageSize) => {
        // 页码改变的回调
        this.setState({ nowPage: page, pageNum: pageSize });
        this.getList(page, pageSize);
      },
      onShowSizeChange: (current, size) => {
        // 单页条数变化的回调
        this.setState({ nowPage: current, pageNum: size });
        this.getList(current, size);
      },
      showTotal: total => {
        const totalPage = total < pagination.pageSize ? 1 : Math.ceil(total / pagination.pageSize);
        return `共 ${total} 条记录 第 ${nowPage} / ${totalPage}页`;
      },
    };
    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 6 } },
      wrapperCol: { md: { span: 16, offset: 1 } },
    };
    // 模态框配置
    const modalConfig = {
      title: isAdd ? '新增联系人信息' : '修改联系人信息',
      visible: modalVisible,
      confirmLoading: loading,
      onOk: this.submitData,
      okText: '提交',
      onCancel: this.cancelModal,
      destroyOnClose: true,
    };
    // 下拉选项
    // 性别
    const genderOL = genderList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    // 是否有小孩
    const hasChildOL = hasChildList.map(options => (
      <Option key={options.itemCode}>{options.itemName}</Option>
    ));
    return (
      <div>
        <Row style={{ marginBottom: '20px' }}>
          <Button type="primary" style={{ marginRight: 20 }} onClick={this.add}>
            <PlusOutlined />
            新增
          </Button>
          <Button
            style={{ marginRight: 20 }}
            icon={<UploadOutlined />}
            onClick={() => router.push(`/salemanage/customer/contactupload?custId=${custId}`)}
          >
            批量上传
          </Button>
          <Button icon={<DownloadOutlined />} onClick={this.export} disabled={cmTotal === 0}>
            导出
          </Button>
        </Row>
        <Table
          rowSelection={rowSelection}
          dataSource={dataSource}
          columns={this.columns}
          rowKey={record => record.contPerId}
          loading={loading}
          pagination={pagination}
        />
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="姓名">
              {getFieldDecorator('name', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={30} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="性别">
              {getFieldDecorator('gender', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <HOCSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {genderOL}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="职位">
              {getFieldDecorator('position', {
                rules: [{ required: true, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={50} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="手机号码">
              {getFieldDecorator('phoneNo', {
                rules: [
                  {
                    required: true,
                    message: '请正确输入手机号码或固话(最大限制12位)',
                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,12}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={12} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="固定电话">
              {getFieldDecorator('tel', {
                rules: [
                  {
                    required: false,
                    message: '固话或手机',
                    pattern: /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{7,14}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={12} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="QQ">
              {getFieldDecorator('qq', {
                rules: [{ required: false, message: '4-12位纯数字', pattern: /^[1-9]\d{4,11}$/ }],
              })(<Input placeholder="请输入" maxLength={12} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="微信">
              {getFieldDecorator('wx', {
                rules: [{ required: false, message: '最多50个字符' }],
              })(<Input placeholder="请输入" maxLength={50} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="邮箱">
              {getFieldDecorator('email', {
                rules: [
                  {
                    type: 'email',
                    required: false,
                    message: '应为邮箱格式且长度不能超过50',
                    pattern: /^[A-Za-z\u4e00-\u9fa5\0-9]{1,50}$/,
                  },
                ],
              })(<Input placeholder="请输入" maxLength={50} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="地址">
              {getFieldDecorator('addr', {
                rules: [{ required: false, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={100} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="生日">
              {getFieldDecorator('birthDay', {
                rules: [{ type: 'object', required: false, message: '请选择' }],
              })(<DatePicker format="YYYY-MM-DD" style={{ width: '100%' }} />)}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="是否有小孩">
              {getFieldDecorator('hasChild', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <HOCSelect
                  placeholder="请选择"
                  style={{ width: '100%' }}
                  allowClear
                  labelInValue
                  showSearch
                  optionFilterProp="children"
                >
                  {hasChildOL}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="备注">
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请输入' }],
              })(<Input placeholder="请输入" maxLength={200} />)}
            </FormItem>
          </Form>
        </Modal>
      </div>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
